<template>
  <div class="content">
    <div class="quantity_detail_content">
      <div class="head" :class="{ layout1: $route.query?.nuclearType === '1', layout2: $route.query?.nuclearType === '2' }">
        <div class="left">
          <div class="title">
            <div class="title_round"></div>
            <div :title="detailInfo.budgetName || '-'" class="text-over" style="width: 100%">
              {{ detailInfo.budgetName || "-" }}
            </div>
          </div>
        </div>
        <div class="right">
          <div class="radio-group-wrap">
            <el-radio-group v-model="topRadioVal" @change="radioGroupChange" v-if="$route.query?.nuclearType === '2'">
              <el-radio-button value="1" size="default">原始工程量核算</el-radio-button>
              <el-radio-button value="2" size="default">变更单核算</el-radio-button>
            </el-radio-group>
          </div>
          <div class="suffix">
            <el-button type="info" class="jzt-button" @click="handleSubmit(true)">返回上一页</el-button>
          </div>
        </div>
      </div>
      <div class="content-inner">
        <!-- 左侧菜单列表 -->
        <div class="anchor">
          <!-- left-空间、综合项、预算汇总菜单列表 -->

          <el-anchor :container="tableList" :offset="100">
            <el-anchor-link class="first_link">
              {{ `空间（${detailInfo.spaceList.length}）` }}
              <template #sub-link>
                <el-anchor-link
                  class="second_link"
                  v-for="item in detailInfo.spaceList"
                  :key="item.spaceId"
                  :href="`#anchor${item.spaceId}`"
                >
                  {{ item.spaceName }}
                </el-anchor-link>
              </template>
            </el-anchor-link>

            <!-- :href="`#comprehensive`" 综合项-->
            <el-anchor-link class="first_link" v-if="topRadioVal === '1'">
              {{ `综合项（${detailInfo.comprehensiveList.length}）` }}
            </el-anchor-link>
            <!-- :href="`#summary`" 预算汇总-->
            <el-anchor-link class="first_link" v-if="topRadioVal === '1'"> 预算汇总 </el-anchor-link>
          </el-anchor>

          <!-- left 悬浮底部 -->
          <div class="left-foot pl15">
            <!-- <div class="mb4" v-if="detailInfo.showGrossProfit === 1"> -->
            <div class="mb4">
              <p class="f12">
                当前订单毛利润：<i style="color: #1a1a1a">{{ `${detailInfo.grossProfitRate || "-"}%` }}</i>
              </p>
              <el-tooltip
                popper-class="action-more"
                effect="dark"
                content="合计总造价 - （材料成本总价+人工费+税金费+管理费+综合项费用总价、都是总价）=订单总销售价-总成本价 除以 / 订单总销售价 （最后等于平均毛利润）"
                placement="right"
              >
                <el-button type="primary" link>
                  <el-icon style="color: #909399"><QuestionFilled /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
            <!-- <div v-if="detailInfo.showGrossProfitLimit === 1"> -->
            <div class="f12">
              订单毛利润限制：<i style="color: #1a1a1a">{{ `${detailInfo.limitGrossProfitRate || "-"}%` }}</i>
            </div>
          </div>
        </div>

        <!-- 右侧内容部分 -->
        <div class="table_list" ref="tableList">
          <div class="right-wrap" :class="{ pd0: topRadioVal === '2' && !isEditChange }">
            <!-- 已核量-有变更数据 -->
            <div class="quantity-over" v-if="topRadioVal === '1' && changeHistoryList?.length > 0">
              <div class="top" :class="{ border: showMoreDetail }">
                <div class="left">
                  <b>
                    {{ changeHistoryList[0]?.nuclearId || "-" }}
                    <span>
                      （ <i>变更金额：</i>¥{{ changeHistoryList[0]?.exchangeMoney || "-" }}
                      <i>&nbsp;&nbsp;&nbsp;&nbsp;退货金额：</i> ¥{{ changeHistoryList[0]?.refundTotalMoney || "-" }}
                      <i> &nbsp;&nbsp;&nbsp;&nbsp;换补单金额：</i> ¥{{ changeHistoryList[0]?.replacementTotalMoney || "-" }}
                      ）
                    </span>
                  </b>
                </div>
                <div class="right">
                  <el-button type="primary" link class="f12" @click="getExchangeNuclearSnapshotFun(changeHistoryList[0])">
                    查看
                  </el-button>
                  <el-divider direction="vertical" v-if="changeHistoryListOther?.length > 0" />
                  <el-button
                    type="primary"
                    @click="showMoreDetail = !showMoreDetail"
                    link
                    v-if="changeHistoryListOther?.length > 0"
                  >
                    <span class="f12 jzt-flex-center">
                      {{ showMoreDetail ? "收起" : "展开" }}
                      <el-icon class="ml4" :class="{ 'arrow-top': showMoreDetail, 'arrow-bottom': !showMoreDetail }"
                        ><ArrowRight
                      /></el-icon>
                    </span>
                  </el-button>
                </div>
              </div>
              <div class="more-wrap" v-if="showMoreDetail && changeHistoryListOther?.length > 0">
                <div class="more-item" v-for="(item, index) in changeHistoryListOther" :key="item.nuclearId">
                  <div class="left">
                    <b>
                      {{ item?.nuclearId || "-" }}
                      <span
                        >（ <i>变更金额：</i>¥{{ item.exchangeMoney || "-" }} <i> &nbsp;&nbsp;&nbsp;&nbsp; 退货金额：</i> ¥{{
                          item.refundTotalMoney || "-"
                        }}
                        <i>&nbsp;&nbsp;&nbsp;&nbsp;换补单金额：</i>¥{{ item.replacementTotalMoney || "-" }} ）</span
                      >
                    </b>
                  </div>
                  <div class="right">
                    <el-button type="primary" link class="f12" @click="getExchangeNuclearSnapshotFun(item)"> 查看 </el-button>
                  </div>
                </div>
              </div>
            </div>

            <!-- radio选中了第1个（原始单） -->
            <template v-if="topRadioVal === '1'">
              <!-- 空间table循环 -->
              <div class="space" v-for="(item, index) in detailInfo.spaceList" :id="`anchor${item.spaceId}`" :key="item.spaceId">
                <div>
                  <div class="title">
                    <div class="title_left">
                      <div class="name">{{ item.spaceName || "--" }}</div>
                      <div class="zone">
                        <span>（合计：</span>
                        <span class="high_light">¥{{ item.spaceTotalMoney || "--" }} / </span>
                        <span>
                          {{
                            `面积：${item.area || "--"}㎡
                      长：${item.length || "--"}m
                      宽：${item.width || "--"}m
                      高：${item.height || "--"}m）`
                          }}
                        </span>
                      </div>
                    </div>

                    <div class="action" v-if="isEditHistory">
                      <div class="material" @click="handleOpenModal(item, true)">
                        <div>材料</div>
                        <img src="@/assets/images/add_material.png" />
                      </div>
                      <div class="split_line"></div>
                      <div class="quota" @click="handleOpenModal(item, false)">
                        <div>定额</div>
                        <img src="@/assets/images/add_material.png" />
                      </div>
                    </div>
                  </div>
                  <div class="table">
                    <el-table
                      v-if="item.quotaItemList?.length > 0"
                      border
                      class="jzt-table"
                      :data="item.quotaItemList"
                      style="width: 100%"
                      header-cell-class-name="table_head"
                      :span-method="temp => tableArraySpan(item.quotaItemList, index, temp)"
                    >
                      <el-table-column type="index" label="序号" fixed="left" width="40" />
                      <el-table-column prop="mainPicUrl" label="图片" fixed="left" width="120">
                        <template #default="{ row }">
                          <div class="img">
                            <template v-if="row.mainPicUrl">
                              <img :src="row.mainPicUrl" alt="" />
                              <img class="icon" v-if="row.exchangeTag === 1" :src="tui" alt="" />
                              <img class="icon" v-if="row.exchangeTag === 2" :src="huan" alt="" />
                              <img class="icon" v-if="row.exchangeTag === 3" :src="bu" alt="" />
                            </template>
                            <span v-else>-</span>
                          </div>
                        </template>
                      </el-table-column>
                      <el-table-column prop="productName" label="商品名称" width="240" />
                      <el-table-column prop="brandName" label="品牌" width="90" />
                      <el-table-column prop="modeCode" label="型号" width="60" />
                      <el-table-column prop="productUnit" label="单位" width="60">
                        <template #default="scope">
                          {{ useCodeArrStore().getDictName("shop_unit", scope.row.productUnit) || "-" }}
                        </template>
                      </el-table-column>
                      <el-table-column prop="num" :label="detailInfo?.budgetType === 2 ? '套餐包含数量' : '数量'" width="120">
                        <template #default="scope">
                          <div class="num-wrap jzt-flex-center">
                            <p>{{ detailInfo?.budgetType === 2 ? scope.row.packageNum : scope.row.num }}</p>
                            <i
                              class="icon f12"
                              :class="{
                                red: scope.row.exchangeTag === 1,
                                orange: scope.row.exchangeTag === 2,
                                blue: scope.row.exchangeTag === 3
                              }"
                              v-if="scope.row.exchangeTag && detailInfo?.budgetType === 1"
                            >
                              {{
                                scope.row.exchangeTag === 1
                                  ? "退"
                                  : scope.row.exchangeTag === 2
                                    ? "换"
                                    : scope.row.exchangeTag === 3
                                      ? "补"
                                      : "-"
                              }}：{{ scope.row.exchangeNum }}
                            </i>
                          </div>
                        </template>
                      </el-table-column>
                      <el-table-column v-if="detailInfo?.budgetType === 2" prop="inscreaseNum" label="增配数量" width="120">
                        <template #default="scope">
                          <div class="num-wrap jzt-flex-center">
                            <p>{{ scope.row.inscreaseNum }}</p>
                            <i
                              class="icon f12"
                              :class="{
                                red: scope.row.exchangeTag === 1,
                                orange: scope.row.exchangeTag === 2,
                                blue: scope.row.exchangeTag === 3
                              }"
                              v-if="scope.row.exchangeTag"
                            >
                              {{
                                scope.row.exchangeTag === 1
                                  ? "退"
                                  : scope.row.exchangeTag === 2
                                    ? "换"
                                    : scope.row.exchangeTag === 3
                                      ? "补"
                                      : "-"
                              }}：{{ scope.row.exchangeNum }}
                            </i>
                          </div>
                        </template>
                      </el-table-column>
                      <el-table-column prop="actualUsedNum" label="实际施工用量" width="180">
                        <template #default="{ row }">
                          <!-- <el-input v-if="isEditHistory" v-model="row.actualUsedNum" @blur="handleChangeActual(row)" /> -->
                          <el-input-number
                            v-if="isEditHistory && row.canEdit"
                            v-model="row.actualUsedNum"
                            class="jzt-input-number jzt-input-number-hidden"
                            controls-position="right"
                            :precision="0"
                            :min="0"
                            :max="detailInfo?.showGrossProfitLimit === 1 ? 999999 : Number(row.num)"
                            placeholder="请输入"
                            @change="handleChangeActual(row)"
                          >
                          </el-input-number>
                          <span v-else>{{ row.actualUsedNum }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="lostRate" label="耗损率" width="90" />
                      <el-table-column v-if="detailInfo.showCost === 1" prop="costUnitPrice" label="成本单价" width="110" />
                      <el-table-column prop="productUnitPrice" label="材料单价" width="110" />
                      <el-table-column prop="workerUnitPrice" label="人工费单价" width="110" />
                      <el-table-column prop="unitTotalMoney" label="单项合计" width="110" />
                      <el-table-column prop="projectVal" label="预算工程量" width="180">
                        <template #default="{ row }">
                          <!-- <el-input
                            v-if="row.isNuclear === 1 && isEditHistory"
                            v-model="row.projectVal"
                            @change="handleChangeProject(row)"
                          /> -->
                          <el-input-number
                            v-if="row.isNuclear === 1 && isEditHistory"
                            v-model="row.projectVal"
                            class="jzt-input-number jzt-input-number-hidden"
                            controls-position="right"
                            :precision="0"
                            :min="0"
                            :max="999999"
                            placeholder="请输入"
                            @change="handleChangeProject(row)"
                          >
                          </el-input-number>
                          <span v-else>{{ row.projectVal }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="projectTotalMoney" label="汇总合计" width="110" />
                      <el-table-column prop="quotaName" label="工程项目名称" width="260" />
                      <el-table-column prop="standardDesc" label="材料及工艺说明" width="130">
                        <template #default="{ row }">
                          <p class="text-over8" style="width: 100%" :title="row.standardDesc">
                            {{ row.standardDesc }}
                          </p>
                        </template>
                      </el-table-column>
                      <el-table-column prop="warrantyTime" label="商品质保日期" width="130">
                        <template #default="{ row }">
                          <span>{{ row.warrantyTime || 0 }}个月</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="remark" label="备注" width="110">
                        <template #default="{ row }">
                          <span v-html="row.remark"></span>
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" width="60">
                        <template #default="{ row }">
                          <span v-if="row.isNuclear === 1 && isEditHistory">
                            <el-popconfirm title="确定要删除该项记录吗？" @confirm="handleDelete(row.id, row.type)">
                              <template #reference>
                                <el-button link type="primary">删除</el-button>
                              </template>
                            </el-popconfirm>
                          </span>
                          <span v-else></span>
                        </template>
                      </el-table-column>
                    </el-table>
                    <el-empty v-else description="这里暂时什么都没有"></el-empty>
                  </div>
                  <div class="memo">
                    <div>备注说明</div>
                    <RemarkEditor v-model="item.remark" :isEdit="false" />
                    <!-- <div class="table_remark" v-html="item.remark" /> -->
                  </div>
                </div>
              </div>

              <div class="block" v-if="detailInfo.spaceList?.length > 0"></div>
              <!-- 综合项 -->
              <div class="space">
                <div id="comprehensive">
                  <div class="title">
                    <div class="title_left">
                      <div class="name">综合项</div>
                      <div class="zone">
                        （合计：
                        <span class="high_light">¥{{ detailInfo?.comprehensiveTotal }}</span>
                        ）
                      </div>
                    </div>
                  </div>
                  <div class="table">
                    <el-table
                      class="jzt-table"
                      :data="detailInfo.comprehensiveList"
                      stripe
                      style="width: 100%"
                      header-cell-class-name="table_head"
                    >
                      <template #empty>
                        <el-empty description="这里暂时什么都没有"></el-empty>
                      </template>
                      <el-table-column type="index" label="序号" fixed="left" width="80" />
                      <el-table-column prop="itemName" label="项目名称" fixed="left" />
                      <el-table-column prop="moneyType" label="属性">
                        <template #default="{ row }">{{ getName("shop_budget_money_type", row.moneyType) }}</template>
                      </el-table-column>
                      <el-table-column prop="unit" label="单位" width="100">
                        <template #default="{ row }">{{ row.unit || "元" }}</template>
                      </el-table-column>
                      <el-table-column prop="linkTypesDesc" label="关联报价" />
                      <el-table-column prop="feeRate" label="单价/比例" />
                      <el-table-column prop="remark" label="说明备注" />
                    </el-table>
                  </div>
                  <div class="tax">
                    <div class="tax_box">
                      <div class="tax_title">
                        <div class="tip">
                          <img src="@/assets/images/tip.png" />
                        </div>
                        <div>管理费</div>
                      </div>
                      <div class="tax_input">
                        <span>比例</span>
                        <el-input disabled style="width: 140px" v-model="detailInfo.managerFeeRate">
                          <template #suffix>%</template>
                        </el-input>
                      </div>
                    </div>
                    <div class="tax_box">
                      <div class="tax_title">
                        <div class="tip">
                          <img src="@/assets/images/tip.png" />
                        </div>
                        <div>税金费用</div>
                      </div>
                      <div class="tax_input">
                        <span>比例</span>
                        <el-input disabled style="width: 140px" v-model="detailInfo.taxesRate">
                          <template #suffix>%</template>
                        </el-input>
                      </div>
                    </div>
                  </div>
                </div>
                <div id="summary">
                  <div class="title">
                    <div class="title_left">
                      <div class="name">预算汇总表</div>
                    </div>
                  </div>
                  <div class="table">
                    <el-table
                      class="jzt-table"
                      :data="detailInfo.budgetSummary.itemList"
                      stripe
                      style="width: 100%"
                      header-cell-class-name="table_head"
                    >
                      <el-table-column type="index" label="序号" fixed="left" width="60" />
                      <el-table-column prop="itemName" label="类别名称" fixed="left" />
                      <el-table-column prop="itemDesc" label="计算明细" />
                      <el-table-column prop="amount" label="价格" />
                    </el-table>
                  </div>
                  <div class="memo">
                    <div>备注说明</div>
                    <RemarkEditor v-model="detailInfo.budgetSummary.remark" :isEdit="false" />
                    <!-- <div class="table_remark" v-html="detailInfo.budgetSummary.remark" /> -->
                  </div>
                </div>
              </div>
            </template>

            <!-- radio选中了第2个（变更单） -->
            <template v-else>
              <ChangeOrderCom
                :optionInfo="optionInfoCom"
                :handleChangeActual="handleChangeActual"
                :handleChangeProject="handleChangeProject"
                :handleDelete="handleDelete"
              >
                <template #headright="{ obj }">
                  <div class="action" v-if="isEditChange">
                    <div class="material" @click="handleOpenModal(obj, true, 'change')">
                      <div>材料</div>
                      <img src="@/assets/images/add_material.png" />
                    </div>
                    <div class="split_line"></div>
                    <div class="quota" @click="handleOpenModal(obj, false, 'change')">
                      <div>定额</div>
                      <img src="@/assets/images/add_material.png" />
                    </div>
                  </div>
                </template>
              </ChangeOrderCom>
            </template>

            <!-- 右边 底部悬浮footer -->
            <!-- 原始工程量 -->
            <div class="affix" v-if="topRadioVal === '1'">
              <el-affix position="bottom" :offset="0" style="width: 100%">
                <div class="affix_content">
                  <div class="transaction">
                    <div class="amount">
                      成交金额：<span class="amount_num">{{ `￥${detailInfo.concludeMoney}` }}</span>
                    </div>
                    <div class="memo">备注：{{ detailInfo.concludeRemark }}</div>
                  </div>
                  <div class="total">
                    <div v-if="detailInfo.budgetType === 1">
                      <p>
                        <span class="total_text">合计总造价：</span>
                        <span class="total_num"> ¥{{ detailInfo.budgetTotlalMoney }} </span>
                        <span class="total_brackets">
                          （
                          <span class="total_detail">
                            {{
                              `房屋总面积：${detailInfo.houseArea}㎡
                      / 空间：${detailInfo.spaceItemNum}个
                      / 综合项：${detailInfo.comprehensiveNum}个
                      / 报价项：${detailInfo.budgetItemNum}项`
                            }}
                          </span>
                          ）
                        </span>
                      </p>
                      <p class="f12 mt10" style="color: #4e5969">
                        <span> 综合项金额：¥{{ detailInfo?.comprehensiveTotal || "-" }} </span>
                        &nbsp;&nbsp;&nbsp;&nbsp; 正价商品：{{ detailInfo?.regularDiscount || "-" }}% / 特价商品：{{
                          detailInfo?.specialDiscount || "-"
                        }}%
                      </p>
                    </div>
                    <div v-else>
                      <span class="total_text">套餐合计：</span>
                      <span class="total_num"> ¥{{ detailInfo.budgetTotlalMoney }} </span>
                      <span class="total_brackets">
                        {{
                          `（套餐价：¥${detailInfo.packageUnitPrice}/㎡
                      可享受：${detailInfo.packageSquareNum}/㎡
                      当前平方：${detailInfo.houseArea}㎡
                      每多出1平方：¥${detailInfo.packageOverUnitPrice}/㎡计算）`
                        }}
                      </span>
                      <div style="margin-top: 10px">
                        <span class="total_detail">
                          {{
                            `超出${detailInfo.overSquareNum}㎡：
                        ¥${detailInfo.overSquareNumMoney}
                        + 个性化增项/配：¥${detailInfo.customIncreaseMoney}
                        + 管理费：¥${detailInfo.managerFee}
                        + 税金费：¥${detailInfo.taxesFee}`
                          }}
                        </span>
                        <span class="f12 mt10 ml20" style="color: #4e5969">
                          综合项金额：¥{{ detailInfo?.comprehensiveTotal || "-" }}
                        </span>
                        <span class="f12 mt10 ml20" style="color: #4e5969">
                          正价商品：{{ detailInfo?.customerRegularDiscount || "-" }}% / 特价商品：{{
                            detailInfo?.customerSpecialDiscount || "-"
                          }}%
                        </span>
                      </div>
                    </div>
                    <div v-if="!(detailInfo?.status === 4) && !($route.query?.readOnly === '1')">
                      <el-button v-if="!isEditHistory" type="primary" @click="isEditHistory = true">继续核量</el-button>
                      <el-button v-else type="primary" @click="handleSubmit(false)">核量完成并提交</el-button>
                    </div>
                  </div>
                </div>
              </el-affix>
            </div>
            <!-- 变更单 -->
            <div class="affix" v-else-if="topRadioVal === '2' && isEditChange">
              <el-affix position="bottom" :offset="0" style="width: 100%">
                <div class="affix_content" :class="{ 'grid-rows': topRadioVal === '2' }">
                  <div class="transaction">
                    <div class="amount">
                      成交金额：<span class="amount_num">{{ `￥${detailInfoChange?.concludeMoney || "-"}` }}</span>
                    </div>
                    <div class="memo">备注：{{ detailInfoChange?.concludeRemark || "-" }}</div>
                  </div>
                  <div class="total">
                    <div v-if="detailInfoChange?.budgetType === 1">
                      <p>
                        <span class="total_text">合计总造价：</span>
                        <span class="total_num"> ¥{{ detailInfoChange?.budgetTotlalMoney || "-" }} </span>
                        <span class="total_brackets">
                          （
                          <span class="total_detail">
                            {{
                              `房屋总面积：${detailInfoChange?.houseArea || "-"}㎡
                      / 空间：${detailInfoChange?.spaceItemNum || "-"}个
                      / 综合项：${detailInfoChange?.comprehensiveNum || "-"}个
                      / 报价项：${detailInfoChange?.budgetItemNum || "-"}项`
                            }}
                          </span>
                          ）
                        </span>
                      </p>
                      <p class="f12 mt10" style="color: #4e5969">
                        <span> 综合项金额：¥{{ detailInfoChange?.comprehensiveTotal || "-" }} </span>
                        &nbsp;&nbsp;&nbsp;&nbsp; 正价商品：{{ detailInfoChange?.regularDiscount || "-" }}% / 特价商品：{{
                          detailInfoChange?.specialDiscount || "-"
                        }}%
                      </p>
                    </div>
                    <div v-else>
                      <span class="total_text">套餐合计：</span>
                      <span class="total_num"> ¥{{ detailInfoChange?.budgetTotlalMoney || "-" }} </span>
                      <span class="total_brackets">
                        {{
                          `（套餐价：¥${detailInfoChange?.packageUnitPrice || "-"}/㎡
                      可享受：${detailInfoChange?.packageSquareNum || "-"}/㎡
                      当前平方：${detailInfoChange?.houseArea || "-"}㎡
                      每多出1平方：¥${detailInfoChange?.packageOverUnitPrice || "-"}/㎡计算）`
                        }}
                      </span>
                      <div style="margin-top: 10px">
                        <span class="total_detail">
                          {{
                            `超出${detailInfoChange?.overSquareNum || "-"}㎡：
                        ¥${detailInfoChange?.overSquareNumMoney || "-"}
                        + 个性化增项/配：¥${detailInfoChange?.customIncreaseMoney || "-"}
                        + 管理费：¥${detailInfoChange?.managerFee || "-"}
                        + 税金费：¥${detailInfoChange?.taxesFee || "-"}`
                          }}
                        </span>
                        <span class="f12 mt10 ml20" style="color: #4e5969">
                          综合项金额：¥{{ detailInfoChange?.comprehensiveTotal || "-" }}
                        </span>
                        <span class="f12 mt10 ml20" style="color: #4e5969">
                          正价商品：{{ detailInfoChange?.regularDiscount || "-" }}% / 特价商品：{{
                            detailInfoChange?.specialDiscount || "-"
                          }}%
                        </span>
                      </div>
                    </div>
                    <div>
                      <el-button type="primary" @click="clickValidate">变更单核量完成</el-button>
                    </div>
                  </div>
                </div>
              </el-affix>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 核量变更单-抽屉 -->
    <ChangeOrder ref="changeOrderRef" v-model:isOpen="_isOpen" :optionInfo="optionInfo" />

    <!-- 导入材料 -->
    <commodityView
      ref="commodityViewRef"
      :show="materialFlag"
      :width="'1200px'"
      @close="materialFlag = false"
      @submit="handelSubmitImport"
    ></commodityView>

    <!-- 导入定额 -->
    <elDrawerView :show="quotaFlag" :title="'选择定额模版'" :size="'80%'" @close="quotaFlag = false">
      <impoQrtuota @getList="item => (quotaIportList = item)"></impoQrtuota>
      <div class="quota_btn pr20">
        <el-button class="jzt-button" type="info" @click="quotaFlag = false">取消</el-button>
        <el-button type="primary" @click="handelQuotaSubmit">已选中:{{ quotaIportList.length }}</el-button>
      </div>
    </elDrawerView>

    <!-- 变更单核量校验 二次确认 -->
    <ActionSubmitDialog
      v-model:isOpen="_isOpenValidate"
      :message="'当前核量单据与之前已生成的合同订单材料数据内容相似，为了避免您重复生成核量单据，请排查后在核量~~'"
      :submitBtnText="'继续提交变更核量'"
      @submit="returnSubmitValidate"
    />
  </div>
</template>
<script setup>
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
import impoQrtuota from "@/views/budgetManagement/components/ImpoQrtuota/index.vue";
import commodityView from "@/views/budgetManagement/components/ImportMaterials/commodityView.vue";
import elDrawerView from "@/views/budgetManagement/components/elDrawerView";
import useCodeArrStore from "@/store/modules/select";
import { ElMessage } from "element-plus";
import {
  getQuantityDetail,
  packageAddQuota,
  packageAddMaterial,
  inventoryAddQuota,
  inventoryAddMaterial,
  updateActualUsedNum,
  updateProjectVal,
  deleteProduct,
  budgetCommit,
  getExchangeNuclearSnapshot
} from "@/apis/budgetQuotation";
import { getExchangeNuclearDetail, validCommit } from "@/apis/quantity";
import { QuestionFilled, ArrowRight } from "@element-plus/icons-vue";
import ChangeOrder from "../components/changeOrder.vue"; //核量变更单-抽屉
import ChangeOrderCom from "../components/changeOrderCom.vue"; //核量变更单-非抽屉
import tui from "@/assets/images/quantity/tui.png";
import huan from "@/assets/images/quantity/huan.png";
import bu from "@/assets/images/quantity/bu.png";
import RemarkEditor from "@/components/RemarkEditor";
import ActionSubmitDialog from "@/components/ActionSubmitDialog";
import { _throttle } from "@/utils";

const _isOpenValidate = ref(false);
const changeOrderRef = ref();
const isEditHistory = ref(true); //原始核量单是否可编辑  query.status：1-待核量 4-待审核的时候，可以直接编辑
const isEditChange = ref(true); //变更核量单是否可编辑  query.status：1-待核量 3-已拒绝，可以直接编辑
const getName = (dictType, code) => useCodeArrStore().getDictName(dictType, code);
const detailInfo = ref({
  spaceList: [],
  comprehensiveList: [],
  budgetSummary: {
    itemList: []
  }
});
const detailInfoChange = ref({});
const shTextarea = ref(""); //审核通过、拒绝时，填写的备注信息
const topRadioVal = ref(route.query?.nuclearType || "1");
const _isOpen = ref(false);
const optionInfo = ref({
  spaceArr: [],
  isSpace: true
});
const optionInfoCom = ref({
  data: {},
  isSpace: true
});
const tableList = ref();
const currentSpace = ref("");
const materialFlag = ref(false);
const quotaFlag = ref(false);
const quotaIportList = ref([]);
const showMoreDetail = ref(false);
const changeHistoryList = ref([]); //变更单历史list
const changeHistoryListOther = ref([]); //变更单历史list，排除第一条数据

onMounted(() => {});

//变更单核量校验-打开二次弹窗
const clickValidate = _throttle(() => {
  validCommit({ nuclearId: detailInfoChange.value?.nuclearId }).then(res => {
    if (res.code === 200) {
      console.log(111111, res.data);
      if (!res.data.validResult) {
        // false有问题(和另一个订单相似度比较高)，弹出校验提示框
        _isOpenValidate.value = true;
      } else {
        // true没问题，直接请求提交接口
        handleSubmit(false, "change");
      }
    }
  });
}, 5000);

//变更单核量校验-二次弹窗，确认继续提交变更核量
const returnSubmitValidate = () => {
  _isOpenValidate.value = false;
  handleSubmit(false, "change");
};

//查询变更单记录快照数据
const getExchangeNuclearSnapshotFun = obj => {
  _isOpen.value = true;
  changeOrderRef.value.setLoading(true);
  getExchangeNuclearSnapshot({ nuclearId: obj.nuclearId }).then(res => {
    if (res.code === 200) {
      console.log("这是快照数据===", res.data);
      optionInfo.value.title = obj.nuclearId;
      optionInfo.value.spaceDetail = res.data;
      optionInfo.value.spaceArr = res.data.nuclearExchangeSpaceVOS;
      changeOrderRef.value.setLoading(false);
    }
  });
};

const radioGroupChange = val => {
  console.log("单选钮切换了", val);
  if (val === "2") {
    // 变更单核算-详情查询
    getDetailInfoChange();
  } else {
    getDetailInfo(route.query.contractId);
  }
};

//检测路由是否存在readOnly，如果存在，整个详情页面为只读状态
const checkIsEdit = () => {
  const _readOnly = route.query.readOnly;
  if (_readOnly === "1") {
    isEditHistory.value = false;
    isEditChange.value = false;
  }
};

//查询原始单
const getDetailInfo = async id => {
  console.log(id);
  let { data } = await getQuantityDetail(id);
  detailInfo.value = data;
  isEditHistory.value = [1, 2, 3].includes(detailInfo.value?.status) ? true : false;
  checkIsEdit();
  changeHistoryList.value = data?.exchangeNuclearRecordVOList || []; //变更单历史list-可以“查看”快照详情抽屉
  changeHistoryListOther.value = [...changeHistoryList.value].slice(1); //变更单历史list，排除第一条数据
  console.log("变更单记录列表===", detailInfo.value.spaceList);

  // detailInfo.value.spaceList.map((item, index) => {
  //   getSpanArr(item?.quotaItemList || [], index);
  // });
};

//查询变更单
const getDetailInfoChange = () => {
  getExchangeNuclearDetail({ nuclearId: route.query.nuclearId }).then(res => {
    if (res.code === 200) {
      console.log("这是变更单详情===", res.data);
      optionInfoCom.value.data = res.data;
      detailInfoChange.value = res.data;

      detailInfo.value.budgetType = res.data?.budgetType || null;
      detailInfo.value.budgetId = res.data?.budgetId || "";
      detailInfo.value.budgetName = res.data?.budgetName || "-";
      detailInfo.value.spaceList = res.data?.nuclearExchangeSpaceVOS;
      detailInfo.value.grossProfitRate = res.data?.grossProfitRate;
      detailInfo.value.limitGrossProfitRate = res.data?.limitGrossProfitRate;

      isEditChange.value = [1, 3].includes(detailInfoChange.value?.status) ? true : false;
      checkIsEdit();
    }
  });
};

const changeObj = ref({});
const handleOpenModal = (item, isMaterial, type = "") => {
  if (type === "change") {
    changeObj.value = { ...item };
  } else {
    changeObj.value = {};
  }
  currentSpace.value = item.spaceId;
  if (isMaterial) materialFlag.value = true;
  else quotaFlag.value = true;
};

//确认导入材料
const handelSubmitImport = async list => {
  let apiFun = null;
  (detailInfo.value.budgetType === 1 || detailInfoChange.value.budgetType === 1) && (apiFun = inventoryAddMaterial); //常规清单
  (detailInfo.value.budgetType === 2 || detailInfoChange.value.budgetType === 2) && (apiFun = packageAddMaterial); //套餐

  const params = {
    skuIds: list.map(item => item.businessSkuId),
    spaceId: currentSpace.value,
    budgetId: detailInfo.value.budgetId
  };
  if (JSON.stringify(changeObj.value) !== "{}") {
    // 如果在变更单添加材料
    params.fromType = 2;
    params.nuclearId = changeObj.value?.nuclearId;
  }
  let { code } = await apiFun(params);
  if (code === 200) {
    handleSuccess("材料添加成功");
    if (JSON.stringify(changeObj.value) !== "{}") {
      // 如果在变更单添加材料
      radioGroupChange("2");
    }
  }
  materialFlag.value = false;
};

const handelQuotaSubmit = async () => {
  let apiFun = null;
  detailInfo.value.budgetType === 1 && (apiFun = inventoryAddQuota);
  detailInfo.value.budgetType === 2 && (apiFun = packageAddQuota);

  const params = {
    quotaIds: quotaIportList.value.map(item => item.quotaId),
    spaceId: currentSpace.value,
    budgetId: detailInfo.value.budgetId
  };
  if (JSON.stringify(changeObj.value) !== "{}") {
    // 如果在变更单添加材料
    params.fromType = 2;
    params.nuclearId = changeObj.value?.nuclearId;
  }

  let { code } = await apiFun(params);
  if (code === 200) {
    handleSuccess("定额添加成功");
    if (JSON.stringify(changeObj.value) !== "{}") {
      // 如果在变更单添加材料
      radioGroupChange("2");
    }
  }
  quotaFlag.value = false;
};

const handleChangeActual = async (row, fromType = 1, key = "actualUsedNum", exchangeType = null) => {
  let params = {
    id: row.id,
    type: row.type,
    fromType: fromType,
    nuclearId: exchangeType ? detailInfoChange.value.nuclearId : detailInfo.value.nuclearId
  };
  params[key] = row[key];
  if (exchangeType) {
    params["exchangeType"] = exchangeType;
  }
  let { code } = await updateActualUsedNum(params);
  code === 200 && handleSuccess("修改成功");
};

const handleChangeProject = async (row, fromType = 1) => {
  let { code } = await updateProjectVal({
    contentId: row.contentId,
    projectVal: row.projectVal,
    fromType: fromType
  });
  code === 200 && handleSuccess("修改成功");
};

const handleDelete = async (id, type, fromType = 1) => {
  let { code } = await deleteProduct({ id, type, fromType: fromType });
  code === 200 && handleSuccess("删除成功");
};

const handleSubmit = async (back = false, type = "") => {
  if (back) {
    router.back();
  } else {
    let { code } = await budgetCommit({
      nuclearId: type === "change" ? detailInfoChange.value.nuclearId : detailInfo.value.nuclearId
    });
    code === 200 && handleSuccess("核量提交成功");
  }
};

const handleSuccess = (message, type = "success") => {
  ElMessage({ type, message });
  topRadioVal.value === "1" && getDetailInfo(route.query.contractId);
  topRadioVal.value === "2" && getDetailInfoChange();
};

const spanArr1 = ref([]);
const pos1 = ref(0);
const spanArr2 = ref([]);
const pos2 = ref(0);
const spanArr3 = ref([]);
const pos3 = ref(0);
const spanArr4 = ref([]);
const pos4 = ref(0);
const spanArrTotal = ref([]); //多个table的时候，把spanArr按照index顺序写入spanArrTotal，
const getSpanArr = (data, tableIndex) => {
  spanArr1.value = []; //初始化数组，防止多次调用时出bug
  pos1.value = 0; //初始化数据，防止多次调用时出bug
  spanArr2.value = [];
  pos2.value = 0;
  spanArr3.value = [];
  pos3.value = 0;
  spanArr4.value = [];
  pos4.value = 0;
  for (let i = 0; i < data.length; i++) {
    if (i === 0) {
      spanArr1.value.push(1);
      spanArr2.value.push(1);
      spanArr3.value.push(1);
      spanArr4.value.push(1);
      pos1.value = 0;
      pos2.value = 0;
      pos3.value = 0;
      pos4.value = 0;
    } else {
      // 判断当前元素与上一个元素是否相同
      //备注
      if (data[i]["remark"] === data[i - 1]["remark"]) {
        spanArr4.value[pos4.value] += 1;
        spanArr4.value.push(0);
      } else {
        spanArr4.value.push(1);
        pos4.value = i;
      }
      //材料及工艺
      if (data[i]["standardDesc"] === data[i - 1]["standardDesc"]) {
        spanArr3.value[pos3.value] += 1;
        spanArr3.value.push(0);
      } else {
        spanArr3.value.push(1);
        pos3.value = i;
      }

      //工程项目名
      if (data[i]["quotaName"] === data[i - 1]["quotaName"]) {
        spanArr2.value[pos2.value] += 1;
        spanArr2.value.push(0);
      } else {
        spanArr2.value.push(1);
        pos2.value = i;
      }

      //汇总合计
      if (data[i]["projectTotalMoney"] === data[i - 1]["projectTotalMoney"]) {
        spanArr1.value[pos1.value] += 1;
        spanArr1.value.push(0);
      } else {
        spanArr1.value.push(1);
        pos1.value = i;
      }
    }
  }
  spanArrTotal.value[tableIndex] = {
    spanArr1: spanArr1.value,
    spanArr2: spanArr2.value,
    spanArr3: spanArr3.value,
    spanArr4: spanArr4.value
  };
};

let contentIdList = [];
const tableArraySpan = (table, nouse, { row, rowIndex, columnIndex }) => {
  let span;
  if (!table) return;

  //汇总合计
  // if ([15].indexOf(columnIndex) > -1) {
  //   const _row = spanArrTotal.value[tableIndex].spanArr1[rowIndex];
  //   const _col = _row > 0 ? 1 : 0;
  //   return [_row, _col];
  // }
  // //工程项目名称
  // if ([16].indexOf(columnIndex) > -1) {
  //   const _row = spanArrTotal.value[tableIndex].spanArr2[rowIndex];
  //   const _col = _row > 0 ? 1 : 0;
  //   return [_row, _col];
  // }
  // //材料及工艺说明
  // if ([17].indexOf(columnIndex) > -1) {
  //   const _row = spanArrTotal.value[tableIndex].spanArr3[rowIndex];
  //   const _col = _row > 0 ? 1 : 0;
  //   return [_row, _col];
  // }
  // //备注
  // if ([18].indexOf(columnIndex) > -1) {
  //   const _row = spanArrTotal.value[tableIndex].spanArr4[rowIndex];
  //   const _col = _row > 0 ? 1 : 0;
  //   return [_row, _col];
  // }

  let arr = [13, 14, 15, 16, 17];
  if (detailInfo.value?.budgetType === 2) {
    arr = [14, 15, 16, 17, 18];
  }

  if (arr.indexOf(columnIndex) > -1) {
    if (!row.contentId) return;
    if (contentIdList[columnIndex] === row.contentId) span = [0, 1];
    else {
      contentIdList[columnIndex] = row.contentId;
      const rows = table.filter(item => {
        return item.contentId === contentIdList[columnIndex];
      });
      const count = rows.length;
      if (count > 1) {
        span = [count, 1];
      }
    }

    if (rowIndex === table.length - 1) contentIdList[columnIndex] = null;

    return span;
  }
};

(() => {
  topRadioVal.value === "1" && getDetailInfo(route.query.contractId);
  topRadioVal.value === "2" && getDetailInfoChange();
})();
</script>
<style lang="scss" scoped>
.text-over8 {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 8; //控制在3行显示
  -webkit-box-orient: vertical;
}
:deep(.file) {
  .draggable_content {
    .content {
      margin-top: 0;
    }
  }
}
.block {
  height: 20px;
  background-color: #f5f7fa;
}
:deep(.el-drawer__body) {
  padding: 0 !important;
}
:deep(.my-drawer) {
  .el-drawer__body {
    padding: 20px !important;
  }
}
.num-wrap {
  height: 80px;
  .icon {
    position: absolute;
    top: 0px;
    left: 0px;
    color: white;
    border-radius: 0 0 4px 0;
    line-height: 20px;
    padding: 0 4px;
    &.red {
      background-color: #d54941;
    }
    &.orange {
      background-color: #ff9900;
    }
    &.blue {
      background-color: #007dff;
    }
  }
}
:deep(.el-anchor__link) {
  &.is-active {
    color: #007dff !important;
    background-color: #d9e8ff !important;
  }
}
.content {
  height: 100%;
}
.quantity_detail_content {
  height: 100%;

  .head {
    width: 100%;
    height: 60px;
    // border-bottom: 1px solid #c2d4e8;
    padding: 0;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .left {
      width: 200px;
      height: 100%;
      border-right: 1px solid #c2d4e8;
      border-bottom: 1px solid #c2d4e8;
      box-sizing: border-box;
      display: flex;
      padding-left: 20px;
    }
    .right {
      flex: 1;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 20px;
      height: 99%;
      border-bottom: 1px solid #c2d4e8;
    }

    &.layout1 {
      .left {
        border-right: 1px solid transparent;
      }
    }
    &.layout2 {
      .left {
        border-bottom: 1px solid transparent;
      }
    }
    :deep(.el-radio-group) {
      .el-radio-button__inner {
        background-color: white !important;
      }
      .el-radio-button.is-active {
        .el-radio-button__inner {
          color: #007dff !important;
        }
      }
    }
    .title {
      display: flex;
      align-items: center;
      font-size: 18px;
      color: #131414;
      font-weight: 700;
      width: 100%;
      .title_round {
        width: 6px;
        height: 6px;
        border-radius: 50%;
        background: #409eff;
        margin-right: 11px;
      }
    }
    .suffix {
      display: flex;
      gap: 40px;
      line-height: 24px;
      .rate_text {
        display: flex;
        color: #3d3d3d;
        text-align: right;
        .tip {
          margin-right: 10px;
        }
      }
      .rate {
        font-weight: 700;
        color: #1a1a1a;
      }
    }
  }
  .content-inner {
    display: grid;
    grid-template-columns: 200px calc(100% - 200px);
    height: calc(100% - 60px);
    // height: calc(100% - 0px);

    .action {
      display: flex;
      color: #007dff;
      gap: 20px;
      .split_line {
        border-left: 1px solid #e1e6ed;
        margin: 3px 0;
      }
      .material,
      .quota {
        display: flex;
        align-items: center;
        gap: 10px;
      }
    }
    .anchor {
      position: relative;
      border-right: 1px solid #c2d4e8;
      padding: 10px 0px;
      :deep(.el-anchor__list) {
        padding: 0;
      }
      :deep(.el-anchor__marker) {
        opacity: 0 !important;
      }
      .first_link {
        :deep(.el-anchor__link) {
          padding: 6px 20px;
          font-weight: 700;
          font-size: 14px;
          color: #3d3d3d;
        }
        .is-active {
          color: #007dff;
          background: #d9e8ff;
        }
        .second_link {
          :deep(.el-anchor__link) {
            font-size: 14px;
            font-weight: 400;
            color: #4e5969;
            background: #f2f3f5;
          }
          .is-active {
            color: #007dff;
            background: #d9e8ff;
          }
        }
      }

      .left-foot {
        position: absolute;
        bottom: 1px;
        left: 0;
        right: 0;
        background-color: white;
        height: 67px;
        border-top: 1px solid #e1e6ed;
        display: flex;
        flex-direction: column;
        justify-content: center;
        border-radius: 0 0 0 10px;
        & > div {
          display: flex;
          align-items: center;
          color: #3d3d3d;
        }
      }
    }
    .table_list {
      height: 100%;
      overflow: auto;
      box-sizing: border-box;
      // background: #f5f7fa;
      .row_img {
        display: block;
        width: 80px;
        height: 80px;
        margin: 0 auto;
        border-radius: 4px;
      }
      .space {
        padding: 20px;
        // margin-bottom: 20px;
        background: white;
        .title {
          display: flex;
          justify-content: space-between;
          .title_left {
            display: flex;
            font-size: 18px;
            color: #3d3d3d;
            align-items: end;
            .name {
              font-weight: 700;
            }
            .zone {
              font-size: 14px;
              color: #4e5969;
              line-height: 18px;
              .high_light {
                color: #ff3333;
              }
            }
          }
        }
        .table {
          margin: 20px 0;
          border: 1px solid #e1e6ed;
          :deep(.el-table__cell) {
            position: relative;
          }
          :deep(.cell) {
            overflow: visible;
            .img {
              img {
                width: 80px;
                height: 80px;
              }
              .icon {
                position: absolute;
                width: 28px;
                height: auto;
                left: 0;
                top: 0;
              }
            }
          }

          .table_head {
            background: #f2f6fc;
          }
        }
        .memo {
          display: grid;
          grid-template-columns: 60px 1fr;
          align-items: center;
          gap: 10px;
          color: #4e5969;
          .table_remark {
            border: 1px solid #e1e6ed;
            padding: 10px 18px;
          }
        }
        .tax {
          display: flex;
          gap: 20px;
          margin-bottom: 30px;
          .tax_box {
            width: 270px;
            .tax_title {
              display: flex;
              align-items: center;
              margin-bottom: 20px;
              font-size: 18px;
              font-weight: 700;
              color: #3d3d3d;
              .tip {
                margin-right: 10px;
              }
            }
            .tax_input {
              display: flex;
              gap: 10px;
              align-items: center;
            }
          }
        }
      }
      .right-wrap {
        // background: #f5f7fa;
        padding-bottom: 135px;
        .quantity-over {
          min-height: 50px;
          position: sticky;
          top: 0;
          z-index: 22;
          background-color: white;
          box-shadow: 4px 5px 16px 0px rgba(4, 19, 74, 0.05);
          & > div {
            padding: 0 20px;
          }
          & > div.top {
            display: flex;
            justify-content: space-between;
            align-items: center;
            &.border {
              border-bottom: 1px solid #e1e6ed;
            }
          }
          :deep(.arrow-top) {
            transform: rotate(-90deg);
            transition: transform 0.2s ease-in-out;
          }
          :deep(.arrow-bottom) {
            transform: rotate(90deg);
            transition: transform 0.2s ease-in-out;
          }
          .top {
            height: 50px;
          }
          .more-wrap {
            .more-item {
              width: 100%;
              height: 50px;
              display: flex;
              justify-content: space-between;
              align-items: center;
            }
          }
          .left {
            b {
              i {
                color: #86909c;
              }
            }
          }
        }
      }
      .affix {
        position: absolute;
        right: 0;
        left: 200px;
        bottom: 0;
        z-index: 22;
        .affix_content {
          box-sizing: border-box;
          display: grid;
          grid-template-columns: 100%;
          grid-template-rows: 64px 68px;
          background: white;
          box-shadow: 0px -5px 10px 0px rgba(66, 78, 102, 0.15);
          &.grid-rows {
            // grid-template-rows: 0px 68px;
            // .total {
            //   height: 68px;
            //   box-sizing: border-box;
            // }
          }
          .transaction {
            padding: 10px 20px;
            line-height: 24px;
            border-bottom: 1px solid #c2d4e8;
            .amount {
              font-weight: 700;
              color: #606266;
              .amount_num {
                color: #3d3d3d;
              }
            }
            .memo {
              font-size: 12px;
              color: #86909c;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              width: calc(100% - 40px);
            }
          }
          .total {
            display: flex;
            align-items: center;
            padding: 20px;
            justify-content: space-between;
            font-size: 16px;
            .total_text {
              color: #606266;
            }
            .total_num {
              color: #ff3333;
            }
            .total_brackets {
              font-size: 14px;
              color: #86909c;
            }
            .total_detail {
              font-size: 12px;
              color: #86909c;
            }
          }
        }
      }
    }
  }
  .el-input {
    border: 1px solid #dcdfe6;
  }
  .el-input__wrapper {
    background: white;
  }
}
.quota_btn {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 10px 0px;
  background: #ffffff;
  box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
  // border-radius: 0px 0px 0px 10px;
}
</style>
